package com.lzm.ydpt.module.mall.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.byt.framlib.base.BaseFragment;
import com.byt.framlib.baseadapter.lv.LvCommonAdapter;
import com.byt.framlib.baseadapter.lv.LvViewHolder;
import com.byt.framlib.baseadapter.rv.RvCommonAdapter;
import com.byt.framlib.baseadapter.rv.RvViewHolder;
import com.byt.framlib.basemvp.basebean.ListPageBean;
import com.byt.framlib.basemvp.boby.FormBodys;
import com.byt.framlib.commonutils.MoneyUtil;
import com.byt.framlib.commonutils.image.ImageLoaderUtils;
import com.byt.framlib.commonutils.rx.RxBus;
import com.byt.framlib.commonwidget.LoadingTip;
import com.byt.framlib.commonwidget.NoScrollGridView;
import com.byt.framlib.commonwidget.NormalTitleBar;
import com.byt.framlib.commonwidget.OnNoDoubleClickListener;
import com.byt.framlib.commonwidget.RoundedConnerImageView;
import com.byt.framlib.commonwidget.onclicktwo.AntiShake;
import com.byt.framlib.commonwidget.selectordialog.dialog.DialogOnClickListener;
import com.byt.framlib.commonwidget.selectordialog.dialog.NormalAlertDialog;
import com.lzm.ydpt.Constants;
import com.lzm.ydpt.R;
import com.lzm.ydpt.entity.mall.ProductBean;
import com.lzm.ydpt.entity.mall.ProductCartBus;
import com.lzm.ydpt.entity.mall.ShopGoods;
import com.lzm.ydpt.module.mall.activity.ProductDetailsActivity;
import com.lzm.ydpt.module.mall.activity.ProductListActivity;
import com.lzm.ydpt.module.mall.utils.ProductUtil;
import com.lzm.ydpt.mvp.contract.MallCartContract;
import com.lzm.ydpt.mvp.presenterimpl.MallCartPresenterImpl;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 商城购物车
 */
public class MallCartFragment extends BaseFragment<MallCartPresenterImpl> implements MallCartContract.View {

    @BindView(R.id.ntb_product_cart)
    NormalTitleBar ntb_product_cart;
    @BindView(R.id.ltip_product_cart)
    LoadingTip ltip_product_cart;
    @BindView(R.id.tv_product_cart_count)
    TextView tv_product_cart_count;
    @BindView(R.id.ll_mall_cart_content)
    LinearLayout ll_mall_cart_content;
    @BindView(R.id.rv_product_cart_data)
    RecyclerView rv_product_cart_data;

    @BindView(R.id.ll_total_price_info)
    LinearLayout ll_total_price_info;
    @BindView(R.id.img_all_product)
    ImageView img_all_product;
    @BindView(R.id.tv_total_price)
    TextView tv_total_price;
    @BindView(R.id.tv_go_pay)
    TextView tv_go_pay;
    @BindView(R.id.tv_delete_cart)
    TextView tv_delete_cart;

    @BindView(R.id.sv_mall_cart_empty)
    ScrollView sv_mall_cart_empty;
    @BindView(R.id.ll_guess_like_layout)
    LinearLayout ll_guess_like_layout;
    @BindView(R.id.gv_guess_like)
    NoScrollGridView gv_guess_like;

    private List<ShopGoods> mGoodsList = new ArrayList<>();
    private RvCommonAdapter<ShopGoods> goodsAdapter = null;
    private List<ShopGoods> selectGoods = new ArrayList<>();

    private boolean isManage = false;

    /**
     * 计算商品总价格，操作步骤
     * 1.先清空全局计价,计数
     * 2.遍历所有的子元素，只要是被选中的，就进行相关的计算操作
     * 3.给textView填充数据
     */
    private String mTotalPrice = "";
    private int mTotalCount = 0;

    private static MallCartFragment sFragment;

    private List<ProductBean> mProductList = new ArrayList<>();
    private LvCommonAdapter<ProductBean> productAdapter = null;

    public static MallCartFragment newsInstance() {
        sFragment = new MallCartFragment();
        return sFragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_mall_cart;
    }

    @Override
    public MallCartPresenterImpl initPresenter() {
        return new MallCartPresenterImpl(this);
    }

    @Override
    protected void initView() {
        initTitle();
        initAdapter();
//        ltip_product_cart.setLoadingTip(LoadingTip.LoadStatus.loading);
//        onProductCartList();
        addSubscription(RxBus.getDefault().toObservableSticky(ProductCartBus.class).subscribe(cartNumBus -> {
            onProductCartList();
        }));
    }

    private void initTitle() {
        ntb_product_cart.setTitleText("购物车");
        ntb_product_cart.setLeftImagVisibility(false);
        ntb_product_cart.setBarLineVisibility(true);
        ntb_product_cart.setRightTitle("管理");
        ntb_product_cart.setRightTitleVisibility(true);
        ntb_product_cart.setOnRightTextListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                isManage = !isManage;
                if (isManage) {
                    ntb_product_cart.setRightTitle("完成");
                    ll_total_price_info.setVisibility(View.GONE);
                    tv_go_pay.setVisibility(View.GONE);
                    tv_delete_cart.setVisibility(View.VISIBLE);
                } else {
                    ntb_product_cart.setRightTitle("管理");
                    ll_total_price_info.setVisibility(View.VISIBLE);
                    tv_go_pay.setVisibility(View.VISIBLE);
                    tv_delete_cart.setVisibility(View.GONE);
                }
                goodsAdapter.notifyDataSetChanged();
            }
        });
    }

    private void initAdapter() {
        rv_product_cart_data.setLayoutManager(new LinearLayoutManager(context));
        goodsAdapter = new RvCommonAdapter<ShopGoods>(context, mGoodsList, R.layout.item_shop_cat_product) {
            @Override
            protected void convert(RvViewHolder viewHolder, ShopGoods product, int position) {
                viewHolder.setText(R.id.tv_product_name, product.getTitle());
                viewHolder.setText(R.id.tv_cart_product_price, String.valueOf(product.getPrice_rmb()));
                viewHolder.setText(R.id.tv_product_num, String.valueOf(product.getTotal()));
                ImageLoaderUtils.display(viewHolder.getView(R.id.img_product_pic), product.getImage_src());
                viewHolder.setText(R.id.tv_product_prime, product.getSpec_title());
                //避免无限次的append
                ImageView img_single_check = viewHolder.getView(R.id.img_single_check);
                if (isManage) {
                    img_single_check.setVisibility(View.VISIBLE);
                    img_single_check.setSelected(product.isSelect());
                    viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            product.setSelect(!product.isSelect());
                            checkChildData(position);
                        }
                    });
                } else {
                    img_single_check.setVisibility(View.GONE);
                }
                viewHolder.setOnClickListener(R.id.img_increase_product, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 增加数量
                        int count = product.getTotal();
                        count++;
                        onShoppingCartNum(product.getCart_id(), product.getOption_id(), count, position);
                    }
                });
                viewHolder.setOnClickListener(R.id.img_reduce_product, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int count = product.getTotal();
                        if (count == 1) {
                            return;
                        }
                        count--;
                        onShoppingCartNum(product.getCart_id(), product.getOption_id(), count, position);
                    }
                });
                viewHolder.getConvertView().setOnClickListener(new OnNoDoubleClickListener() {
                    @Override
                    protected void onNoDoubleClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putLong(Constants.INP_PRODUCT_ID, product.getGoods_id());
                        openActivity(ProductDetailsActivity.class, bundle);
                    }
                });
            }
        };
        rv_product_cart_data.setAdapter(goodsAdapter);

        productAdapter = new LvCommonAdapter<ProductBean>(context, mProductList, R.layout.item_product_grid_layout) {
            @Override
            protected void convert(LvViewHolder viewHolder, ProductBean productBean, int position) {
                RoundedConnerImageView img_product_pic = viewHolder.getView(R.id.img_product_pic);
                ImageLoaderUtils.display(img_product_pic, productBean.getImage_src());
                viewHolder.setText(R.id.tv_product_name, productBean.getTitle());
                viewHolder.setText(R.id.tv_product_desc, productBean.getFunctional_indications());
                viewHolder.setText(R.id.tv_product_sell_price, productBean.getMin_price() + "");
                viewHolder.setText(R.id.tv_product_sales, "已售300");
                viewHolder.getConvertView().setOnClickListener(new OnNoDoubleClickListener() {
                    @Override
                    protected void onNoDoubleClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putLong(Constants.INP_PRODUCT_ID, productBean.getGoods_id());
                        openActivity(ProductDetailsActivity.class, bundle);
                    }
                });
            }
        };
        gv_guess_like.setAdapter(productAdapter);
    }

    private void onProductCartList() {
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("api_token", "");
        formBodys.add("id", 0);
        mPresenter.onProductCartList(formBodys.build());
    }

    private void onDeteleCart(String cart_ids, List<ShopGoods> tempList) {
        startProgressDialog();
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("id", 0);
        formBodys.add("cart_id", cart_ids);
        mPresenter.onDeteleProductCart(formBodys.build(), tempList);
    }

    private void onShoppingCartNum(long cart_id, long option_id, int quantity, int position) {
        startProgressDialog();
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("cart_id", cart_id);
        formBodys.add("option_id", option_id);
        formBodys.add("quantity", quantity);
        mPresenter.onShoppingCart(formBodys.build(), position, quantity);
    }

    private void getProductList() {
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("id", 0);
        mPresenter.onShopGuessLike(formBodys.build());
    }

    @Override
    public void showMessage(String message, String method) {
        stopProgressDialog();
        showShortToast(message);
    }

    @Override
    public void showErrorView(String msg) {
        showErrorView(msg, ltip_product_cart);
        ltip_product_cart.setOnReloadListener(new LoadingTip.onReloadListener() {
            @Override
            public void reload(View view) {
                ltip_product_cart.setLoadingTip(LoadingTip.LoadStatus.loading);
                onProductCartList();
            }
        });
    }

    @OnClick({R.id.rl_all_product, R.id.tv_go_pay, R.id.tv_go_shopping, R.id.tv_delete_cart})
    public void OnClick(View v) {
        if (AntiShake.check(v.getId())) {
            return;
        }
        switch (v.getId()) {
            case R.id.rl_all_product:
                doCheckAll();
                break;
            case R.id.tv_go_shopping:
                openActivity(ProductListActivity.class);
                break;
            case R.id.tv_go_pay:
                //去结算
                List<ShopGoods> shopGoods = getSelectList();
                if (shopGoods != null && shopGoods.size() > 0) {
                    Bundle bundle = new Bundle();
                    String goodRequest = ProductUtil.goodRequestData(shopGoods);
//                    bundle.putString(FillOrderActivity.INP_ORDER_PRODUCT_LIST, goodRequest);
//                    openActivity(FillOrderActivity.class, bundle);
                } else {
                    showShortToast("请选择商品");
                }
                break;
            case R.id.tv_delete_cart:
                NormalAlertDialog normalAlertDialog = new NormalAlertDialog.Builder(context)
                        .setButtonTextSize(14)
                        .setTitleVisible(false)
                        .setTitleTextSize(16)
                        .setContentText("是否要删除选中的商品")
                        .setLeftButtonText("我再想想")
                        .setLeftButtonTextColor(R.color.color_333333)
                        .setRightButtonText("删除")
                        .setRightButtonTextColor(R.color.color_main)
                        .setContentTextSize(14)
                        .setContentTextColor(R.color.color_333333)
                        .setOnclickListener(new DialogOnClickListener() {

                            @Override
                            public void clickLeftButton(View view) {

                            }

                            @Override
                            public void clickRightButton(View view) {
                                StringBuffer stringBuffer = new StringBuffer();
                                for (ShopGoods shopGoo : selectGoods) {
                                    if (!TextUtils.isEmpty(stringBuffer.toString())) {
                                        stringBuffer.append("," + shopGoo.getCart_id());
                                    } else {
                                        stringBuffer.append(shopGoo.getCart_id());
                                    }
                                }
                                onDeteleCart(stringBuffer.toString(), selectGoods);
                            }
                        })
                        .build();
                normalAlertDialog.show();
                break;
        }
    }

    private List<ShopGoods> getSelectList() {
        List<ShopGoods> shopGoods = new ArrayList<>();
        for (ShopGoods goods : mGoodsList) {
            if (goods.isSelect()) {
                shopGoods.add(goods);
            }
        }
        return shopGoods;
    }

    /**
     * 全选和反选
     * 错误标记：在这里出现过错误
     */
    private void doCheckAll() {
        img_all_product.setSelected(!img_all_product.isSelected());
        for (int i = 0; i < mGoodsList.size(); i++) {
            ShopGoods group = mGoodsList.get(i);
            group.setSelect(img_all_product.isSelected());
        }
        goodsAdapter.notifyDataSetChanged();
        calulate();
    }

    /**
     * @param position 组元素的位置
     */
    private void checkChildData(int position) {
        ShopGoods goods = mGoodsList.get(position);
        goods.setSelect(!goods.isSelect());//如果子元素状态相同，那么对应的组元素也设置成这一种的同一状态
        img_all_product.setSelected(isCheckAll());//全选 反选
        goodsAdapter.notifyDataSetChanged();
        calulate();
    }

    /**
     * @return 判断组元素是否全选
     */
    private boolean isCheckAll() {
        for (ShopGoods group : mGoodsList) {
            if (!group.isSelect()) {
                return false;
            }
        }
        return true;
    }

    private void calulate() {
        mTotalPrice = "0.0";
        mTotalCount = 0;
        for (int i = 0; i < mGoodsList.size(); i++) {
            ShopGoods good = mGoodsList.get(i);
            if (good.isSelect()) {
                mTotalCount += good.getTotal();
                mTotalPrice = MoneyUtil.add(mTotalPrice, MoneyUtil.mul(good.getPrice_rmb(), String.valueOf(good.getTotal())));
            }
        }
        tv_total_price.setText(String.valueOf(mTotalPrice));
        tv_go_pay.setText("去结算(" + mTotalCount + ")");
    }

    @Override
    public void onProductCartList(ListPageBean<ShopGoods> cartProductList) {
        if (cartProductList != null && cartProductList.getList() != null && cartProductList.getList().size() > 0) {
            ltip_product_cart.setLoadingTip(LoadingTip.LoadStatus.finish);
            mGoodsList.clear();
            mGoodsList.addAll(cartProductList.getList());
            goodsAdapter.notifyDataSetChanged();
            tv_product_cart_count.setText("共" + cartProductList.getTotal() + "件商品");
            calulate();
            ll_mall_cart_content.setVisibility(View.VISIBLE);
            sv_mall_cart_empty.setVisibility(View.GONE);
        } else {
            getProductList();
            ll_mall_cart_content.setVisibility(View.GONE);
            sv_mall_cart_empty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDeteleProductCart(String msg, List<ShopGoods> tempList) {
        stopProgressDialog();
        showShortToast(msg);
        RxBus.getDefault().postSticky(new ProductCartBus());
        for (ShopGoods tempGoods : tempList) {
            mGoodsList.remove(tempGoods);
        }
        goodsAdapter.notifyDataSetChanged();
    }

    @Override
    public void onShoppingCart(String msg, int position, int num) {
        stopProgressDialog();
        mGoodsList.get(position).setTotal(num);
        goodsAdapter.notifyDataSetChanged();
        calulate();
    }

    @Override
    public void onShopGuessLike(ListPageBean<ProductBean> productList) {
        mProductList.clear();
        mProductList.addAll(productList.getList());
        productAdapter.notifyDataSetChanged();
        if (mProductList.size() > 0) {
            ll_guess_like_layout.setVisibility(View.VISIBLE);
        } else {
            ll_guess_like_layout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroyView() {
        sFragment = null;
        super.onDestroyView();
    }
}